﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Messages;
using System.ServiceModel;

namespace RibbonEditor.Managers
{
    public class MetadataManager
    {
        List<EntityMetadata> entityCache;

        public MetadataManager(IOrganizationService service)
        {
            try
            {
                RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest();
                request.EntityFilters = EntityFilters.Entity;

                RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)service.Execute(request);

                this.entityCache = new List<EntityMetadata>();

                foreach (EntityMetadata emd in response.EntityMetadata)
                {
                    this.entityCache.Add(emd);
                }
            }
            catch (Exception error)
            {
                if (error.InnerException != null && error.InnerException is FaultException)
                {
                    throw new Exception("Error while retrieving solutions: " + ((FaultException)error.InnerException).Message);
                }
                else
                {
                    throw new Exception("Error while caching metadata: " + error.Message);
                }
            }
        }
     
        public List<EntityMetadata> EntityCache
        {
            get { return entityCache; }
            set { entityCache = value; }
        }
    }
}
